package com.stuManager.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stuManager.dao.UserDao;
import com.stuManager.model.CommonResponseModel;
import com.stuManager.model.User;
import com.stuManager.service.LoginService;
import com.stuManager.util.ReadPostBodyUtil;
import com.stuManager.util.UserTokenUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/*
    LoginServlet
    账号密码登录接口
    登录成功后将会生成一个token，设置到cookie中
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取一个service
        LoginService service = new LoginService();
        //获取post参数
        String requestBody = ReadPostBodyUtil.getPostData(request);
        User user = JSON.parseObject(requestBody.toString(), User.class);
        CommonResponseModel m = new CommonResponseModel();
        try {
            //尝试使用参数中的user登录
            m = service.loginService(user);
            if (m.getErrorCode() == 0) {
                JSONObject json = (JSONObject) m.getResult();
                Cookie cookie = new Cookie("token", json.getString("token"));
                //设置cookie使用期限
                cookie.setMaxAge(60 * 60);
                response.addCookie(cookie);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        String jsonString = JSON.toJSONString(m);
        response.setContentType("application/json");
        response.getWriter().print(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
